import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:raze/artifacts/helper_function.dart';
import 'package:raze/artifacts/loader_aura.dart';
import 'package:raze/artifacts/notifier_glimmer.dart';
import 'package:raze/lore/chronicle/user_chronicle.dart';
import 'package:raze/potions/raze_constant.dart';
import 'package:raze/potions/spatial_alchemy.dart';

/// 注册页
class RegisterRealms extends StatefulWidget {
  const RegisterRealms({super.key});

  @override
  State<RegisterRealms> createState() => _RegisterRealmsState();
}

class _RegisterRealmsState extends State<RegisterRealms> {
  final _accountController = TextEditingController();
  final _passwordController = TextEditingController();
  final _passwordAgainController = TextEditingController();
  final _userChronicle = Get.find<UserChronicle>();

  @override
  void dispose() {
    _accountController.dispose();
    _passwordController.dispose();
    _passwordAgainController.dispose();
    super.dispose();
  }

  /// 执行注册
  void _executeRegister() {
    final account = _accountController.text.trim();
    final password = _passwordController.text.trim();
    final passwordAgain = _passwordAgainController.text.trim();

    if (account.isEmpty) {
      NotifierGlimmer.revealWarning('Please enter your account name');
      return;
    }

    if (password.isEmpty) {
      NotifierGlimmer.revealWarning('Please enter your password');
      return;
    }

    if (passwordAgain.isEmpty) {
      NotifierGlimmer.revealWarning('Please confirm your password');
      return;
    }

    if (password != passwordAgain) {
      NotifierGlimmer.revealWarning('Passwords do not match');
      return;
    }

    LoaderAura.unveilProgress();

    Future.delayed(const Duration(milliseconds: 800), () {
      LoaderAura.concealProgress();

      // 使用账号名作为用户名，可以后续优化
      final success = _userChronicle.performRegister(
        account,
        password,
        account,
        'New user',
        'assets/images/avatar1.png',
      );

      if (success) {
        NotifierGlimmer.revealSuccess('Registration successful');
        // 自动登录
        _userChronicle.performLogin(account, password);
        // 这里可以跳转到主页
      } else {
        NotifierGlimmer.revealFailure('Account already exists');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: RazeConstants.background,
      body: SafeArea(
        child: LayoutBuilder(
          builder: (context, constraints) {
            final screenHeight = constraints.maxHeight;
            final screenWidth = constraints.maxWidth;

            // 计算顶部区域高度
            final topAreaHeight = 16.h + 30.w + 10.h + 76.w;

            // 计算底部法律文本高度
            final bottomTextHeight =
                32.h + 24.h + 20.h; // padding + text height

            // 计算可用高度
            final availableHeight =
                screenHeight - topAreaHeight - bottomTextHeight;

            // 容器宽度（左右各16.w间距）
            final containerWidth = screenWidth - 32.w;
            // 根据宽高比计算的容器高度
            final containerHeightByRatio = containerWidth * (458 / 343);

            // 使用较小的值，确保内容不超出屏幕
            final containerHeight =
                containerHeightByRatio > availableHeight
                    ? availableHeight
                    : containerHeightByRatio;

            return Column(
              children: [
                // 顶部区域
                Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // 返回按钮行
                    Padding(
                      padding: EdgeInsets.only(top: 16.h, left: 16.w),
                      child: Row(
                        children: [
                          Container(
                            width: 30.w,
                            height: 30.w,
                            decoration: BoxDecoration(
                              color: RazeConstants.background,
                              borderRadius: BorderRadius.circular(8.r),
                              border: Border.all(
                                color: RazeConstants.black,
                                width: 2.w,
                              ),
                            ),
                            child: Icon(
                              Icons.chevron_left_rounded,
                              color: RazeConstants.black,
                              size: 24.sp,
                            ),
                          ).withRightBottomShadow().withTouchResonance(
                            onTap: () {
                              Get.back();
                            },
                          ),
                        ],
                      ),
                    ),
                    // Logo行
                    Padding(
                      padding: EdgeInsets.only(top: 10.h),
                      child: Center(
                        child: Image.asset(
                          'assets/images/small-logo.png',
                          width: 76.w,
                          height: 76.w,
                          fit: BoxFit.contain,
                        ),
                      ),
                    ),
                  ],
                ),

                20.h.boxHeight,

                // 主要内容区域
                Flexible(
                  child: Container(
                    width: containerWidth,
                    height: containerHeight,
                    margin: EdgeInsets.symmetric(horizontal: 16.w),
                    child: Stack(
                      children: [
                        // 背景图片
                        Image.asset(
                          'assets/images/auth-container.png',
                          width: containerWidth,
                          height: containerHeight,
                          fit: BoxFit.fill,
                        ),
                        // 内容
                        Positioned.fill(
                          child: Padding(
                            padding: EdgeInsets.all(24.w),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                // 标题
                                Text('Register')
                                    .applyTypeSize(32.sp)
                                    .applyTypeColor(RazeConstants.white)
                                    .applyBagelFatOne(
                                      weight: FontWeight.bold,
                                      shadows: [
                                        Shadow(
                                          offset: const Offset(2, 2),
                                          blurRadius: 0,
                                          color: RazeConstants.black,
                                        ),
                                        Shadow(
                                          offset: const Offset(-2, -2),
                                          blurRadius: 0,
                                          color: RazeConstants.black,
                                        ),
                                        Shadow(
                                          offset: const Offset(2, -2),
                                          blurRadius: 0,
                                          color: RazeConstants.black,
                                        ),
                                        Shadow(
                                          offset: const Offset(-2, 2),
                                          blurRadius: 0,
                                          color: RazeConstants.black,
                                        ),
                                      ],
                                    ),
                                20.h.boxHeight,

                                // 账号输入框
                                Container(
                                  decoration: BoxDecoration(
                                    color: RazeConstants.white,
                                    borderRadius: BorderRadius.circular(12.r),
                                    border: Border.all(
                                      color: RazeConstants.black,
                                      width: 1.5.w,
                                    ),
                                  ),
                                  child: TextField(
                                    controller: _accountController,
                                    decoration: InputDecoration(
                                      hintText: 'Account Name',
                                      hintStyle: TextStyle(
                                        color: RazeConstants.black.withOpacity(
                                          0.5,
                                        ),
                                        fontSize: 14.sp,
                                      ),
                                      border: InputBorder.none,
                                      contentPadding: EdgeInsets.symmetric(
                                        horizontal: 16.w,
                                        vertical: 14.h,
                                      ),
                                    ),
                                    style: TextStyle(
                                      color: RazeConstants.black,
                                      fontSize: 14.sp,
                                    ),
                                  ),
                                ),
                                16.h.boxHeight,

                                // 密码输入框
                                Container(
                                  decoration: BoxDecoration(
                                    color: RazeConstants.white,
                                    borderRadius: BorderRadius.circular(12.r),
                                    border: Border.all(
                                      color: RazeConstants.black,
                                      width: 1.5.w,
                                    ),
                                  ),
                                  child: TextField(
                                    controller: _passwordController,
                                    obscureText: true,
                                    decoration: InputDecoration(
                                      hintText: 'Password',
                                      hintStyle: TextStyle(
                                        color: RazeConstants.black.withOpacity(
                                          0.5,
                                        ),
                                        fontSize: 14.sp,
                                      ),
                                      border: InputBorder.none,
                                      contentPadding: EdgeInsets.symmetric(
                                        horizontal: 16.w,
                                        vertical: 14.h,
                                      ),
                                    ),
                                    style: TextStyle(
                                      color: RazeConstants.black,
                                      fontSize: 14.sp,
                                    ),
                                  ),
                                ),
                                16.h.boxHeight,

                                // 确认密码输入框
                                Container(
                                  decoration: BoxDecoration(
                                    color: RazeConstants.white,
                                    borderRadius: BorderRadius.circular(12.r),
                                    border: Border.all(
                                      color: RazeConstants.black,
                                      width: 1.5.w,
                                    ),
                                  ),
                                  child: TextField(
                                    controller: _passwordAgainController,
                                    obscureText: true,
                                    decoration: InputDecoration(
                                      hintText: 'Password Again',
                                      hintStyle: TextStyle(
                                        color: RazeConstants.black.withOpacity(
                                          0.5,
                                        ),
                                        fontSize: 14.sp,
                                      ),
                                      border: InputBorder.none,
                                      contentPadding: EdgeInsets.symmetric(
                                        horizontal: 16.w,
                                        vertical: 14.h,
                                      ),
                                    ),
                                    style: TextStyle(
                                      color: RazeConstants.black,
                                      fontSize: 14.sp,
                                    ),
                                  ),
                                ),
                                16.h.boxHeight,

                                // 登录链接
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: [
                                    Text(
                                      'Already have an account? Go ',
                                      style: TextStyle(
                                        color: RazeConstants.white,
                                        fontSize: 12.sp,
                                      ),
                                    ),
                                    GestureDetector(
                                      onTap: () {
                                        Get.back();
                                      },
                                      child: Text(
                                        'Log In',
                                        style: TextStyle(
                                          color: RazeConstants.darkYellow,
                                          fontSize: 12.sp,
                                          decoration: TextDecoration.underline,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                                20.h.boxHeight,

                                // 注册按钮
                                Container(
                                  width: double.infinity,
                                  height: 58.h,
                                  decoration: BoxDecoration(
                                    color: RazeConstants.blue,
                                    borderRadius: BorderRadius.circular(12.r),
                                    border: Border.all(
                                      color: RazeConstants.black,
                                      width: 2.w,
                                    ),
                                  ),
                                  child: Center(
                                    child: Text('Register')
                                        .applyTypeSize(20.sp)
                                        .applyTypeColor(RazeConstants.white)
                                        .applyBagelFatOne(
                                          weight: FontWeight.w400,
                                          shadows: [
                                            Shadow(
                                              offset: const Offset(1, 1),
                                              blurRadius: 0,
                                              color: RazeConstants.black,
                                            ),
                                            Shadow(
                                              offset: const Offset(-1, -1),
                                              blurRadius: 0,
                                              color: RazeConstants.black,
                                            ),
                                            Shadow(
                                              offset: const Offset(1, -1),
                                              blurRadius: 0,
                                              color: RazeConstants.black,
                                            ),
                                            Shadow(
                                              offset: const Offset(-1, 1),
                                              blurRadius: 0,
                                              color: RazeConstants.black,
                                            ),
                                          ],
                                        ),
                                  ),
                                ).withTouchResonance(onTap: _executeRegister),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),

                // 底部法律文本
                Padding(
                  padding: EdgeInsets.only(top: 32.h, bottom: 24.h),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        'By Continuing you agree with ',
                        style: TextStyle(
                          color: RazeConstants.black.withOpacity(0.5),
                          fontSize: 12.sp,
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          HelperFunction.launchUrl(
                            RazeConstants.termsOfServiceUrl,
                          );
                        },
                        child: Text(
                          'Terms of Service',
                          style: TextStyle(
                            color: RazeConstants.black,
                            fontSize: 11.sp,
                            decoration: TextDecoration.underline,
                          ),
                        ),
                      ),
                      Text(
                        ' & ',
                        style: TextStyle(
                          color: RazeConstants.black.withOpacity(0.5),
                          fontSize: 11.sp,
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          HelperFunction.launchUrl(
                            RazeConstants.privacyPolicyUrl,
                          );
                        },
                        child: Text(
                          'Privacy Policy',
                          style: TextStyle(
                            color: RazeConstants.black,
                            fontSize: 11.sp,
                            decoration: TextDecoration.underline,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}
